package ydzhao.weixin.tuisong.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

public class GuessMi {
    private static String key = "xxx";
    private static String url = "http://api.tianapi.com/zimi/index?key=";
    private static List<String> jinJuList = new ArrayList<>();

    /**
     * 猜谜底
     * @return
     */
    public static Map<String,String> getGuessMi() {
        TreeMap<String,String> map = new TreeMap<>();
        //猜谜底
        String content = "";
        String answer = "";
        String reason = "";
        try {
            JSONObject jsonObject = JSONObject.parseObject(HttpUtil.getUrl(url+key));
            if (jsonObject.getIntValue("code") == 200) {
                content = jsonObject.getJSONArray("newslist").getJSONObject(0).getString("content");
                answer = jsonObject.getJSONArray("newslist").getJSONObject(0).getString("answer");
                reason = jsonObject.getJSONArray("newslist").getJSONObject(0).getString("reason");
                map.put("content",content);
                map.put("answer",answer);
                map.put("reason",reason);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 载入金句库
     */
    static {
        InputStream inputStream = GuessMi.class.getClassLoader().getResourceAsStream("jinju.txt");
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
            String str = "";
            String temp = "";
            while ((temp = br.readLine()) != null) {
                if (!StringUtils.isEmpty(temp)) {
                    str = str + "\r\n" + temp;
                } else {
                    jinJuList.add(str);
                    str = "";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getJinJu() {
        Random random = new Random();
        return jinJuList.get(random.nextInt(jinJuList.size()));
    }

    public static void main(String[] args) throws Exception {
//        System.out.println(getJinJu());
//        System.out.println(HttpUtil.getUrl(url+key));
        System.out.println(getGuessMi());
    }
}
